<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <PageTools>
          <template #left>
            <slot name="left">
              <div class="left">
                <div class="tips">
                  <i class="el-icon-info" />
                  <span>总记录数: {{ total }} 条</span>
                </div>
              </div>
            </slot>
          </template>
          <template #right>
            <slot name="right">
              <div class="right">
                <el-button

                  type="warning"

                  size="small"
                  @click="$router.push('/import')"
                >导入Excel</el-button>
                <el-button v-loading="loading" element-loading-spinner="el-icon-loading" type="danger" size="small" @click="hExportExcel">导出Excel</el-button>
                <!-- @click="hExportExcel" -->
                <el-button
                  type="primary"
                  size="small"
                  @click="showDialog = true"
                >新增员工</el-button>
              </div>
            </slot>
          </template>
        </PageTools>
      </el-card>
      <el-card style="margin-top: 12px">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="workNumber" sortable label="工号" />
          <!-- 头像 -->
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImgHolder :url="scope.row.staffPhoto" />
              <!-- <img src="scope.row.staffPhoto"> -->
            </template>

          </el-table-column>
          <el-table-column label="聘用形式">
            <!-- 枚举 , 插槽 -->
            <template slot-scope="scope">
              类型 {{ formatEmploy(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.timeOfEntry) }}
            </template>

          </el-table-column>
          <el-table-column label="操作" style="width:400px">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="role(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="del(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          style="height: 60px; margin-top: 10px"
          layout="prev, pager, next"
          :total="total"
          :page-size="params.size"
          :current-page="params.page"
          @current-change="currentChange"
        />
      </el-card>
      <el-dialog
        :visible.sync="showDialog"
        title="编辑员工"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hCloseDialog"
      >
        <Addemployees
          ref="exitFn"
          @updateEmpolyee="loadEmployeeList"
          @closes="showDialog = false"
        />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        :visible.sync="showDialog2"
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assignRole :cur-id="curId" @ @close-dialog="showDialog2=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>

import assignRole from './assignRole'
import Addemployees from './Addemployees'
import { reqGetEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
// 枚举
// {id:1,value:'正式'}  {id:2,value:'非正式'}
// 转化为   {" 1 " : "正式" }  {" 2 " : "非正式" }
const hireType = {}
EmployeeEnum.hireType.forEach((item) => {
  hireType[item.id] = item.value
})
console.log('枚举信息', EmployeeEnum.hireType, hireType)
export default {
  components: {
    Addemployees,
    assignRole
  },
  data() {
    return {
      curId: '', // 分配角色id
      loading: false, // 转圈
      showDialog: false, // 弹框
      showDialog2: false, // 分配角色弹框
      tableData: [
        //   {
        //   username: '',
        //   formOfEmployment: '',
        //   workNumber: '',
        //   departmentName: '',
        //   timeOfEntry: ''
        // }
      ],
      total: 0,
      params: {
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 枚举
    // {id:1,value:'正式'}  {id:2,value:'非正式'}
    // 转化为 **策略模式**  {" 1 " : "正式" }  {" 2 " : "非正式" }
    formatEmploy(id) {
      return hireType[id]
    },
    formatDate(oldDate) {
      return oldDate.substr(0, 10) // 只取前面10个字符
    },
    hCloseDialog() {
      console.log('在父组件中获取子组件的引用', this.$refs.exitFn)
      this.$refs.exitFn.exit()
    },
    // 分配角色
    role(id) {
      this.showDialog2 = true
      this.curId = id
    },
    // 把当前页导出数据
    /**
     * 现状：
     *   arr: [
     *      {mobile: "136121221", username:"管理员"}，
     *      {mobile: "136121224", username:"小王"}
     *   ]
     * 目标：
     *   header: ['手机号', '姓名']]
     *   data: [
     *        ["136121221", "管理员"],
     *        ["136121224", "小王"],
     *    ]
     */
    transData(arr) {
      // 把formOfEmployment中的1改成正式， 2改成非正式
      arr.forEach(item => {
        if (item.formOfEmployment) {
          // 1 --> 正式
          // 2 --> 非正式
          item.formOfEmployment = hireType[item.formOfEmployment]
        }
      })
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出数组中第一个元素，来根据key生成对应的中文
      const first = arr[0]
      const header = Object.keys(first).map(item => map[item])
      console.log('表头是', header)
      const data = arr.map(obj => {
        return Object.values(obj)
      })
      console.log('数据是', data)
      return { header, data }
    },
    // 把当前页的数据导出来，保存成excel文件
    // 有一个现成的工具：/vendor/Export2Excel
    hExportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        this.loading = true
        const res = await reqGetEmployeeList(this.params)
        console.log('导出export', res.data.rows)
        const { header, data } = this.transData(res.data.rows)
        excel.export_json_to_excel({
          header, // 表头 必填   ["姓名", "手机号"]
          data, // 数据      [ ["小王", "13797979782"],  ["小李", "13798779782"]]
          filename: 'test-export-excel', // 文件名
          autoWidth: true, // 自动设置列的宽度
          bookType: 'xlsx' // 文件类型
        })
        this.loading = false
      })
    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 点击删除
    async doDel(id) {
      const res = await delEmployee(id)
      console.log('删除的', res)
      if (this.tableData.length === 1) {
        this.params.page--
        if (this.params.page === 0) {
          this.params.page === 1
        }
      }
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      const res = await reqGetEmployeeList(this.params)
      console.log('获取的员工列表', res)
      // this.tableData = res.data.rows
      // this.total = this.data.total
      // 新方法
      const { total, rows } = res.data
      this.total = total
      this.tableData = rows
    },
    currentChange(newPage) {
      this.params.page = newPage
      this.loadEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
